// chrome.webRequest.onBeforeRequest.addListener(
//   function(details) {
//     console.log('Intercepted Fetch request: ', details.url, details.method)
//   },
//   { urls: ['<all_urls>'] },
//   ['blocking']
// )

// var currentTab;
// var version = "1.0";

// chrome.tabs.query( //get current Tab
//   {
//       currentWindow: true,
//       active: true
//   },
//   function(tabArray) {
//       currentTab = tabArray[0];
//       // chrome.debugger.attach({ //debug at current tab
//       //     tabId: currentTab.id
//       // }, version, onAttach.bind(null, currentTab.id));
//       console.log('current tab: ', currentTab)
//       if(!currentTab.url.startsWith("chrome:")) {
//         chrome.debugger.attach(
//           { 
//             //debug at current tab                     
//             tabId: currentTab.id
//           }, 
//           version, 
//           onAttach.bind(null, currentTab.id)
//         );          
//       }

//   }
// )


// function onAttach(tabId) {
//     chrome.debugger.sendCommand({ //first enable the Network
//         tabId: tabId
//     }, "Network.enable");
//     chrome.debugger.onEvent.addListener(allEventHandler);
// }


// function allEventHandler(debuggeeId, message, params) {
//   console.log('current allEventHandler: ', debuggeeId, message, params)
//   if (currentTab.id != debuggeeId.tabId) {
//       return;
//   }
//   if (message == "Network.responseReceived") { //response return 
//       chrome.debugger.sendCommand({
//           tabId: debuggeeId.tabId
//       }, "Network.getResponseBody", {
//           "requestId": params.requestId
//       }, function(response) {
//           console.log('============response: ', response)
//           // you get the response body here!
//           // you can close the debugger tips by:
//           chrome.debugger.detach(debuggeeId);
//       });
//   }
// }

// chrome.devtools.network.onRequestFinished.addListener(
//   function(request) {
//     console.log('response ------',request.response)
//     request.getContent((body) => {
//       if (request.request && request.request.url) {
//         if (request.request.url.includes('facebook.com')) {
  
//            //continue with custom code
//            var bodyObj = JSON.parse(body);//etc.
//            console.log(bodyObj)
//         }
//       }
//     });
//   }
// );


var currentTab;
var version = "1.0";
var requestMethod = '';

// 当前浏览器活跃的tab
chrome.tabs.onActivated.addListener(activeTab => {
    // 相当于移除监听，不移除直接监听可能会重复监听同一个tabId导致报错
    currentTab&&chrome.debugger.detach({tabId:currentTab.tabId});
    currentTab = activeTab;
    // 相当于开启监听
    chrome.debugger.attach({ //debug at current tab
        tabId: currentTab.tabId
    }, version, onAttach.bind(null, currentTab.tabId));
});

function onAttach(tabId) {
    // 发送命令，向指定tab开启网络功能
    chrome.debugger.sendCommand({ //first enable the Network
        tabId: tabId
    }, "Network.enable");
    // chrome调试器监听事件，捕获网络请求核响应相关事件
    chrome.debugger.onEvent.addListener(allEventHandler);
}

async function allEventHandler(debuggeeId, message, params) {
    if (currentTab.tabId !== debuggeeId.tabId) {
        return;
    }
    // 功能我只做了一个fetch类型请求的拦截
    if(params.type === 'Fetch') {
        // message里面的信息我理解为一个完整网络请求的生命周期
        if(message === 'Network.requestWillBeSent') {
            requestMethod = params?.request?.method;
        }
        if (message === "Network.responseReceived") { //response return
            const response = await new Promise(resolve => {
                chrome.debugger.sendCommand({
                    tabId: debuggeeId.tabId
                }, "Network.getResponseBody", { "requestId": params.requestId }, resolve);
            });
            if(response?.body) {
                console.log(`${requestMethod} - ${params.response.url} :  `, response.body);
                requestMethod = ''
            }
        }
    }
}